package com.atguigu.controller;

import com.alibaba.druid.sql.visitor.functions.Bin;
import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.Admin;
import com.atguigu.entity.AdminRole;
import com.atguigu.entity.Role;
import com.atguigu.group.AddGroup;
import com.atguigu.group.UpdateGroup;
import com.atguigu.service.AdminRoleService;
import com.atguigu.service.AdminService;
import com.atguigu.service.RoleService;
import com.atguigu.util.FileUtil;
import com.atguigu.util.QiniuUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.management.StringValueExp;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 翟文海
 * @Date: 2022/10/26/026 13:23
 * @Version: 1.0
 * @Description:
 **/
@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {
    private static final String PAGE_INDEX = "admin/index";
    private static final String SUCCESS_PAGE = "common/successPage";
    private static final String PAGE_EDIT = "admin/edit";
    private static final String LIST_ADMIN = "redirect:/admin";
    private static final String PAGE_UDLOAD = "admin/upload";
    private static final String PAGE_ASSIGNSHOW = "admin/assignShow";
    private static final String PAGE_CREAT = "admin/create";
    private static final String PAGE_BINDERROR = "common/bindError";
    @Reference
    private AdminService adminService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Reference
    private AdminRoleService adminRoleService;

    @RequestMapping
    public String index(@RequestParam Map<String, String> filters, Model model) {
        PageInfo<Admin> page = adminService.findPage(filters);
        model.addAttribute("page", page);
        model.addAttribute("filters", filters);
        return PAGE_INDEX;
    }

    @PreAuthorize("hasAnyAuthority('admin.show')")
    @GetMapping("/create")
    public String create(){
        return toPage(PAGE_CREAT);
    }


    @PreAuthorize("hasAnyAuthority('admin.create')")
    @PostMapping("/save")
    public String save(@Validated(value = AddGroup.class) Admin admin, Model model) {
        /*if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            model.addAttribute("fieldErrors",fieldErrors);
            return toPage(PAGE_BINDERROR);
        }*/
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        adminService.insert(admin);
        return toPage(model, "新增用户成功", SUCCESS_PAGE);
    }
    @PreAuthorize("hasAnyAuthority('admin.show')")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, Model model) {

        Admin admin = adminService.getById(id);
        model.addAttribute("admin", admin);
        return PAGE_EDIT;
    }

    @PreAuthorize("hasAnyAuthority('admin.edit')")
    @PostMapping("/update")
    public String update(@Validated(value = UpdateGroup.class) Admin admin, Model model) {
        /*if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            model.addAttribute("fieldErrors",fieldErrors);
            return toPage(PAGE_BINDERROR);
        }*/

        adminService.update(admin);
        return toPage(model, "修改用户成功", SUCCESS_PAGE);
    }
    @PreAuthorize("hasAnyAuthority('admin.delete')")
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id, Model model) {
        adminService.delete(id);
        return LIST_ADMIN;
    }
    @PreAuthorize("hasAnyAuthority('admin.show')")
    @GetMapping("/uploadShow/{id}")
    public String uploadShow(Model model, @PathVariable("id") Long id) {
        model.addAttribute("id", id);
        return toPage(PAGE_UDLOAD);
    }
    @PreAuthorize("hasAnyAuthority('admin.edit')")
    @PostMapping("/upload/{id}")
    public String upload(Model model, @PathVariable("id") Long id, @RequestParam("file") MultipartFile file) throws IOException {
        String uuidName = FileUtil.getUUIDName(file.getOriginalFilename());
        String dirPath = FileUtil.getRandomDirPath(2, 3);
        String fileName = dirPath + uuidName;
        QiniuUtils.upload2Qiniu(file.getBytes(), fileName);
        String url = QiniuUtils.getUrl(fileName);
        Admin admin = new Admin();
        admin.setId(id);
        admin.setHeadUrl(url);
        adminService.update(admin);
        return toPage(model, "上传头像成功", SUCCESS_PAGE);
    }
    @PreAuthorize("hasAnyAuthority('admin.show')")
    @GetMapping("/assignShow/{id}")
    public String assignShow(@PathVariable("id") Long id, Model model) {
        //unAssignRoleList，查找这个用户不是这个角色的列表，根据adminId查找
        //assignRoleList，查找这个用户是这个角色的列表
        Map<String, List<Role>> resultMap = adminRoleService.findRoleListMapByAdminId(id);
        model.addAttribute("adminId", id);
        model.addAllAttributes(resultMap);
        return toPage(PAGE_ASSIGNSHOW);
    }

    /**
     *
     * @param adminId
     * @param roleIds roleIds右边需要分配的权限集合
     * @param model
     * @return
     */
    @PreAuthorize("hasAnyAuthority('admin.edit')")
    @PostMapping("/assignRole")
    public String assignRole(@RequestParam("adminId") Long adminId,
                             @RequestParam("roleIds") List<Long> roleIds,
                             Model model) {
        adminRoleService.assignRole(adminId,roleIds);
        return toPage(model,"添加角色成功",SUCCESS_PAGE);
    }
}
